#!/usr/bin/env python
# -*- coding: UTF-8; indent-tabs-mode:nil; tab-width:4 -*-

# This file is part of DITA DTD Generator.
#
# DITA DTD Generator is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DITA DTD Generator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DITA DTD Generator.  If not, see <http://www.gnu.org/licenses/>.

"""Command line interface to DITA DTD Generator."""

import sys
import os
import re
#import time
#import datetime
#import tempfile
#import tarfile
import ditagen.xml
#import ditagen.dita.v1_2
from ditagen.dita.v1_2 import *
import ditagen.generator
import getopt

DOMAIN_MAP = {
    "ui": ditagen.dita.v1_2.UiDomain,
    "hi": ditagen.dita.v1_2.HiDomain,
    "pr": ditagen.dita.v1_2.PrDomain,
    "sw": ditagen.dita.v1_2.SwDomain,
    "ut": ditagen.dita.v1_2.UtDomain,
    "indexing": ditagen.dita.v1_2.IndexingDomain,
    "learning": ditagen.dita.v1_2.LearningDomain,
    "learningmeta": ditagen.dita.v1_2.LearningMetaDomain,
    "learningmap": ditagen.dita.v1_2.LearningMapDomain,
    "mitask": ditagen.dita.v1_2.MachineIndustryTaskDomain,
    "hazardstatement": ditagen.dita.v1_2.HazardStatementDomain,
    "mapgroup": ditagen.dita.v1_2.MapGroupDomain,
    "abbreviated": ditagen.dita.v1_2.AbbreviatedFormDomain,
    "xnal": ditagen.dita.v1_2.XNALDomain,
    "delay": ditagen.dita.v1_2.UserDelayedResolutionDomain,
    "classify": ditagen.dita.v1_2.ClassifyDomain,
    "taskbody": ditagen.dita.v1_2.MachineIndustryTaskbodyConstraints,
    "strictTaskbody": ditagen.dita.v1_2.StrictTaskbodyConstraints
    }
TOPIC_MAP = {
    "concept": ditagen.dita.v1_2.ConceptType,
    "reference": ditagen.dita.v1_2.ReferenceType,
    "task": ditagen.dita.v1_2.TaskType,
    "topic": ditagen.dita.v1_2.TopicType,
    "machineTask": ditagen.dita.v1_2.MachineryTaskType,
    "map": ditagen.dita.v1_2.MapType,
    "bookmap": ditagen.dita.v1_2.BookMapType,
    "classifyMap": ditagen.dita.v1_2.ClassificationMapType,
    "subjectScheme": ditagen.dita.v1_2.SubjectSchemeMapType,
    "learningAssessment": ditagen.dita.v1_2.LearningAssessmentType,
    "learningBookmap": ditagen.dita.v1_2.LearningBookMapType,
    "learningContent": ditagen.dita.v1_2.LearningContentType,
    "learningMap": ditagen.dita.v1_2.LearningMapType,
    "learningOverview": ditagen.dita.v1_2.LearningOverviewType,
    "learningPlan": ditagen.dita.v1_2.LearningPlanType,
    "learningSummary": ditagen.dita.v1_2.LearningSummaryType
    }

#ARGS = [(("h", "help"), "Print usage help"),
#        (("d:", "domain="), "Domains"),
#        (("o:", "owner="), "Owner in PFI"),
#        (("f:", "format="), "Format, one of 'dtd', or 'zip'")
#       ]

def main():
    """Main method."""
    __domains = []
    __type = None
    __root = None
    __owner = None
    __nested = None
    __remove = {}
    __global_atts = None
    __f = None
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:o:f:", ["help", "domain=", "owner=", "format="])
                                   #"".join(i[0][0] for i in args),
                                   #[i[0][1] for i in args])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage() 
            sys.exit()
        elif opt in ("-d", "--domain"):
            if arg in DOMAIN_MAP:
                __domains.append(DOMAIN_MAP[arg]())
        elif opt in ("-f", "--format"):
            if arg in ("dtd", "zip"):
                __f = arg
        elif opt in ("-o", "--owner"):
            __owner = arg
    for arg in args:
        if arg in TOPIC_MAP:
            __type = TOPIC_MAP[arg]()
    #__nested = u"nested" in __form
    #__remove = dict([(n, True) for n in __form.getlist("remove")])
    #__global_atts = None#__form.getfirst(u"attribute")
    if __f is None:
        __f = "dtd"
    # run generator
    dita_gen = ditagen.generator.DitaGenerator()
    dita_gen.set_output(sys.stdout)
    dita_gen.set_topic_type(__type)
    dita_gen.set_domains(__domains)
    dita_gen.set_root(__root)
    dita_gen.set_owner(__owner)
    dita_gen.set_nested(__nested)
    
    if __f == u"dtd":
        __file_name = dita_gen.get_file_name(__type, __root, __f)
        dita_gen.generate_dtd()
    elif __f == u"mod":
        __file_name = dita_gen.get_file_name(__type, __root, __f)
        dita_gen.print_mod(__type, __domains, __root, __owner, __nested, __remove, __global_atts)
    elif __f == u"tgz":
        __file_name = dita_gen.get_file_name(__type, __root, "tar.gz")
        dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested, __remove, __global_atts)
    elif __f == u"xzip":
        __file_name = dita_gen.get_file_name(__type, __root, "zip")
        zip_dita_gen = ditagen.generator.ZipGenerator(sys.stdout)
        zip_dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested)
    elif __f == u"zip":
        __file_name = dita_gen.get_file_name(__type, __root, "zip")
        dita_gen.generate_zip(sys.stdout)

def usage():
    """Usage."""
    print """Usage: cli.py [OPTIONS]... TOPICS...
DITA DTD Generator commandline tool.

Examples:
  cli.py task
  cli.py -d ui-d -d indexing-d concept -o EXAMPLE.COM task reference"""

if __name__ == "__main__":
    main()
